package com.game.sdk.init;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;

import android.text.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.game.sdk.YTAppService;
import com.game.sdk.domain.ChannelMessage;
import com.game.sdk.domain.ParamJson;
import com.game.sdk.domain.Proclamation;
import com.game.sdk.domain.ResultCode;
import com.game.sdk.shareprefreneces.PreferencesUtils;
import com.game.sdk.ui.ChargeActivity;
import com.game.sdk.util.ActivityTaskManager;
import com.game.sdk.util.Constants;
import com.game.sdk.util.DataSafeUtil;
import com.game.sdk.util.DialogUtil;
import com.game.sdk.util.GetDataImpl;
import com.game.sdk.util.MResource;
import com.game.sdk.util.NetTask;
import com.game.sdk.util.NetworkImpl;
import com.game.sdk.util.Util;

public class InitUtil {
	private static final String TAG = "NetUtil";
	private static InitUtil getdataImpl;
	private static Context ctx;

	private static final int SDK_INIT_FAIL_COUNT = 3;
	public static int SDK_INIT_COUNT = 0;
	public static int PAY_INIT_COUNT = 0;
	private static int CITYID_INIT_COUNT = 0;

	public static final int INIT_SUS = 1;
	private InitUtil(Context ctxs) {
		this.ctx = ctxs;
	}

	public static InitUtil getInstance(Context ctxs) {
		if (null == getdataImpl) {
			getdataImpl = new InitUtil(ctxs);
		}
		if (ctx == null) {
			ctx = ctxs;
		}
		return getdataImpl;
	}

	/**
	 * sdk初始化支付接口
	 * 
	 * @param mHandler
	 * */
	public static void sdkInitpay(final Context acontext, final Handler mHandler) {
		InitUtil.getInstance(acontext).initPay(acontext, new NetCallBack() {

			@Override
			public void onInitSuccess(ResultCode result) {
				try {
					DialogUtil.dismissDialog();
				} catch (Exception e) {
					e.printStackTrace();
				}
//				if(!ActivityTaskManager.getInstance().isLoginStatus(acontext)){
//					
//					return ;
//				}
				try {
					String dataArr = new JSONObject(result.data).getString("a");
					if (!TextUtils.isEmpty(dataArr)) {
						YTAppService.channels = InitUtil.getCustomPay(dataArr);
					}
					PreferencesUtils.saveInitedStatus(true, acontext);
					mHandler.sendEmptyMessage(INIT_SUS);
				} catch (JSONException e) {
					PreferencesUtils.saveInitedStatus(false, acontext);
					e.printStackTrace();
				}
			}

			@Override
			public void onInitFail(ResultCode result) {
				PAY_INIT_COUNT++;
				if (PAY_INIT_COUNT >= SDK_INIT_FAIL_COUNT) {
					PAY_INIT_COUNT = 0;
					Util.showNetFailToast(acontext, "亲，请检查网络", result);
					try {
						DialogUtil.dismissDialog();
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							sdkInitpay(acontext, mHandler);
						}
					});
				}
			}
		});
	}

	/**
	 * sdk初始化通知入口
	 * 
	 * @param mHandler
	 * */
	public static void sdkInitNotice(final Context acontext) {
		InitUtil.getInstance(acontext).initNotice(acontext, new NetCallBack() {

			@Override
			public void onInitSuccess(ResultCode result) {
				if(!ActivityTaskManager.getInstance().isLoginStatus(acontext)){
					try {
						DialogUtil.dismissDialog();
					} catch (Exception e) {
						e.printStackTrace();
					}
					return ;
				}
				String data = result.data;
				if (!TextUtils.isEmpty(data)) {
					try {
						JSONObject o = new JSONObject(data);
						Proclamation proclation = new Proclamation();
						proclation.proid = o.isNull("a") ? 0 : o.getInt("a");
						proclation.title = o.isNull("b") ? "" : o
								.getString("b");
						proclation.content = o.isNull("c") ? "" : o
								.getString("c");
						if (YTAppService.proclation == null) {
							YTAppService.proclation = proclation;
							return;
						}
						if (YTAppService.proclation.proid != proclation.proid) {
							YTAppService.proclation = proclation;
							return;
						}

					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			}

			@Override
			public void onInitFail(ResultCode result) {

			}
		});
	}

	/***
	 * 通知弹框的回调
	 * */
	public static interface NoticeCallBack {
		void onCloseNotice();
	}

	/**
	 * 在登录之前需要一个对话框的话，这么些就方便许多
	 * */
	public static void showNotice(Context acontext, LayoutInflater inflater,
			final NoticeCallBack callBack) {
		if (null != YTAppService.proclation) {
			final Dialog notice_dialog = new Dialog(acontext,
					MResource.getIdByName(acontext, Constants.Resouce.STYLE,
							"customDialog"));
			View gift_view = inflater.inflate(MResource.getIdByName(acontext,
					Constants.Resouce.LAYOUT, "sdk_notice"), null);
			// LayoutParams lp=new
			// LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

			TextView tv_notic_title = (TextView) gift_view
					.findViewById(MResource.getIdByName(acontext,
							Constants.Resouce.ID, "tv_notic_title"));
			TextView tv_notice_content = (TextView) gift_view
					.findViewById(MResource.getIdByName(acontext,
							Constants.Resouce.ID, "tv_notice_content"));
			Button btn_goin = (Button) gift_view.findViewById(MResource
					.getIdByName(acontext, Constants.Resouce.ID, "btn_goin"));
			tv_notic_title.setText(YTAppService.proclation.title);
			tv_notice_content.setText(YTAppService.proclation.content);

			btn_goin.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					notice_dialog.dismiss();
				}
			});
			notice_dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialogbu消失
			notice_dialog.setContentView(gift_view);
			notice_dialog.show();
			notice_dialog.setOnDismissListener(new OnDismissListener() {
				
				@Override
				public void onDismiss(DialogInterface arg0) {
					callBack.onCloseNotice();
				}
			});
		} else {
			callBack.onCloseNotice();
		}
	}

	private static boolean isInitedNotice = false;
	private static boolean isInitedPay = false;
	private static boolean isInitedCityid = false;

	/**
	 * sdk初始化调用接口
	 * */
	public static void sdkInit(final Context acontext, final Handler mHandler) {
		if (!DialogUtil.isShowing()) {
			DialogUtil.showDialog(acontext, "loading...");
		}
		GetDataImpl.PHPSESSID = null;
		PreferencesUtils.saveInitedStatus(false, acontext);
		InitUtil.getInstance(acontext).init(acontext, new NetCallBack() {
			@Override
			public void onInitSuccess(ResultCode result) {
				if(!ActivityTaskManager.getInstance().isLoginStatus(acontext)){
					try {
						DialogUtil.dismissDialog();
					} catch (Exception e) {
						e.printStackTrace();
					}
					return ;
				}
				JSONObject responseData = null;
				try {
					// 能够到这步就表明，result是不为空的并且 result.code==1
					responseData = new JSONObject(result.data);
					YTAppService.checked = responseData.getInt("a");
					YTAppService.ip = responseData.getString("b");
					YTAppService.is_update = responseData.getInt("c");
					YTAppService.url = responseData.getString("d");
					sdkInitpay(acontext, mHandler);
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							sdkInitNotice(acontext);
						}
					}, 30000);
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							getCityId(acontext, mHandler);
						}
					}, 5000);
				} catch (JSONException e1) {
					e1.printStackTrace();
				}

				try {
					if (!"".equals(responseData.getString("e"))) {
						JSONObject dataO = responseData.getJSONObject("e");// 附带的字段（客服信息）
						if (dataO != null) {
							YTAppService.service_qq = dataO.getString("qq");
							YTAppService.service_wx = dataO.getString("wx");
							YTAppService.service_qqGroup = dataO
									.getString("qqgroup");
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
					PreferencesUtils.saveInitedStatus(false, acontext);
				}
			}

			@Override
			public void onInitFail(ResultCode result) {
				PreferencesUtils.saveInitedStatus(false, acontext);
				SDK_INIT_COUNT++;
				if (SDK_INIT_COUNT >= SDK_INIT_FAIL_COUNT) {
					SDK_INIT_COUNT = 0;
					if (DialogUtil.isShowing()) {
						try {
							DialogUtil.dismissDialog();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					Util.showNetFailToast(acontext, "亲，请检查您的网络", result);
				} else {
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							sdkInit(acontext, mHandler);
						}
					}, 1000);
				}
			}
		});

	}

	/***
	 * 拿到ip所在的地区编号
	 * 
	 * @param mHandler
	 * */
	public static void getCityId(final Context acontext, final Handler mHandler) {
		if (NetworkImpl.isNetWorkConneted(ctx)) {
			InitUtil.getCityIdFromAli(new NetCallBack() {
				@Override
				public void onInitSuccess(ResultCode result) {
					if(!ActivityTaskManager.getInstance().isLoginStatus(acontext)){
						try {
							DialogUtil.dismissDialog();
						} catch (Exception e) {
							e.printStackTrace();
						}
						return ;
					}
					String data = result.data;
					if (!TextUtils.isEmpty(data)) {
						try {
							JSONObject o = new JSONObject(data);
							YTAppService.city_id = TextUtils.isEmpty(o
									.getString("city_id")) ? "" : o
									.getString("city_id");
						} catch (JSONException e) {
							e.printStackTrace();
						}

					} else {
						YTAppService.city_id = "";
						Util.showNetFailToast(acontext, "获取城市代号失败了", result);
					}

				}

				@Override
				public void onInitFail(ResultCode result) {
					CITYID_INIT_COUNT++;
					YTAppService.city_id = "";
					if (CITYID_INIT_COUNT >= SDK_INIT_FAIL_COUNT) {
						CITYID_INIT_COUNT = 0;
						//Util.showNetFailToast(acontext, "", result);
					} else {
						mHandler.post(new Runnable() {
							@Override
							public void run() {
								getCityId(acontext, mHandler);
							}
						});
					}
				}
			});
		} else {// 没有网络的话就取消对话框
			try {
				Util.showNetFailToast(ctx, "请检查网络", null);
				DialogUtil.dismissDialog();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * sdk初始化
	 * 
	 * @param jasonStr
	 * @return
	 */
	public void init(final Context ctx, final NetCallBack callback) {
		if (NetworkImpl.isNetWorkConneted(ctx)) {
			String jasonStr = "";
			jasonStr = getInitParamsObj().toString();
			new NetTask() {
				protected void onPostExecute(String result) {
					if (TextUtils.isEmpty(result)) {// 非空判断
						callback.onInitFail(null);
					} else {
						try {
							JSONObject json;
							json = new JSONObject(result);
							ResultCode code = new ResultCode();
							code.parseCommJson(json);
							if (code.code == 1) {
								callback.onInitSuccess(code);
							} else {
								callback.onInitFail(code);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				};
			}.execute(ctx, Constant.URL_INIT, jasonStr, true, true, true, true);
		} else {// 没有网络的话就取消对话框
			try {
				Util.showNetFailToast(ctx, "请检查网络", null);
				DialogUtil.dismissDialog();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * sdk初始化
	 * 
	 * @param jasonStr
	 * @return
	 */
	public void initPay(final Context ctx, final NetCallBack callback) {
		if (NetworkImpl.isNetWorkConneted(ctx)) {
			String jasonStr = "";
			jasonStr = getInitpayParamsObj().toString();
			new NetTask() {

				protected void onPostExecute(String result) {
					Util.netResponseCommHandler(1, result, callback);
				};
			}.execute(ctx, Constant.URL_INIT_PAY, jasonStr, true, true, true,
					true);
		} else {// 没有网络的话就取消对话框
			try {
				Util.showNetFailToast(ctx, "请检查网络", null);
				DialogUtil.dismissDialog();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * sdk初始化
	 * 
	 * @param jasonStr
	 * @return
	 */
	public void initNotice(final Context ctx, final NetCallBack callback) {
		if (NetworkImpl.isNetWorkConneted(ctx)) {
			String jasonStr = "";
			jasonStr = getNoticeParamsObj().toString();
			new NetTask() {

				protected void onPostExecute(String result) {
					Util.netResponseCommHandler(1, result, callback);
				};
			}.execute(ctx, Constant.URL_NOTICE, jasonStr, true, true, true,
					true);
		} else {
			try {
				Util.showNetFailToast(ctx, "请检查网络", null);
				DialogUtil.dismissDialog();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static JSONObject getInitParamsObj() {
		ParamJson json = new ParamJson();
		json.setAppid(YTAppService.appid);
		json.setImei(YTAppService.dm.imeil);
		json.setFrom(ParamJson.ANDROID + "");// android 就用1
		json.setDeviceinfo(YTAppService.dm.deviceinfo);
		json.setUserua(YTAppService.dm.userua);
		json.setCode(DataSafeUtil.code + "");
		json.setClient_id(YTAppService.clientId + "");
		String api_token = DataSafeUtil.getApiToken("init",
				System.currentTimeMillis(), YTAppService.clientKey);
		json.setApi_token(api_token);
		json.setVersion(YTAppService.version);
		json.setParams_key(DataSafeUtil.getIdentifyKey(json.getParamsString(),
				YTAppService.clientKey));

		return json.buildParams();
	}

	/***
	 * 获取通知的参数
	 * */
	public static JSONObject getNoticeParamsObj() {
		ParamJson json = new ParamJson();
		json.setAppid(YTAppService.appid);

		json.setFrom(ParamJson.ANDROID + "");// android 就用1

		json.setCode(DataSafeUtil.code + "");

		json.setClient_id(YTAppService.clientId + "");

		String api_token = DataSafeUtil.getApiToken("notice",
				System.currentTimeMillis(), YTAppService.clientKey);
		json.setApi_token(api_token);

		json.setParams_key(DataSafeUtil.getIdentifyKey(json.getParamsString(),
				YTAppService.clientKey));

		return json.buildParams();
	}

	/***
	 * 获取初始化的参数
	 * */
	public static JSONObject getInitpayParamsObj() {
		ParamJson json = new ParamJson();
		json.setAppid(YTAppService.appid);
		json.setFrom(ParamJson.ANDROID + "");// android 就用1
		json.setCode(DataSafeUtil.code + "");
		json.setClient_id(YTAppService.clientId + "");
		String api_token = DataSafeUtil.getApiToken("initpay",
				System.currentTimeMillis(), YTAppService.clientKey);
		json.setApi_token(api_token);
		json.setParams_key(DataSafeUtil.getIdentifyKey(json.getParamsString(),
				YTAppService.clientKey));

		return json.buildParams();
	}

	/**
	 * 提取获取支付渠道的列表
	 * */
	public static List<ChannelMessage> getCustomPay(String dataArr) {
		List<ChannelMessage> list = new ArrayList<ChannelMessage>();
		boolean hsPtb = false;
		boolean hsGame = false;
		String ptbString = "";
		String gameString = "";
		try {
			JSONArray arr = new JSONArray(dataArr);
			int j = 1;// 下标
			for (int index = 0; index < arr.length(); index++) {
				JSONObject item = (JSONObject) arr.get(index);
				String payway = (String) item.get("a");
				if (!TextUtils.isEmpty(payway)) {
					if (searchPayway(payway)) {
						ChannelMessage channel = new ChannelMessage(j++,
								item.getString("b"), item.getString("b"),
								payway);
						list.add(channel);
						if(payway.contains("ptb")){
							hsPtb = true;
							ptbString = item.getString("b");
						}
						if(payway.contains("game")){
							hsGame = true;
							gameString = item.getString("b");
						}
					}
				} else {
					list = null;// 有坏死的数据
					break;
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
			list = null;
		}
		if (list == null || list.size() <= 0) {
			list = YTAppService.channelsAll;
		}
		if(hsPtb){
			ChargeActivity.payway = ptbString;
		}else{
			ChargeActivity.payway = gameString;
		}
		return list;
	}
	/***
	 * 查看该支付有没有包含在本地的支付列表，有的就返回true。否则就是false
	 * */
	private static boolean searchPayway(String payway) {
		return true;
		// boolean bool = false;
		// for (int i = 0; i < YTAppService.channelsAll.size(); i++) {
		// ChannelMessage item = YTAppService.channelsAll.get(i);
		// if (item.type.equals(payway)) {
		// bool = true;
		// break;
		// }
		// continue;
		// }
		// return bool;
	}

	public static void getCityIdFromAli(final NetCallBack callBack) {
		new NetTask() {
			protected void onPostExecute(String result) {
				Util.netResponseCommHandler(0, result, callBack);
			};
		}.execute(ctx, Constant.URL_CITY_ID + YTAppService.ip, null, false,
				false, false, false);
	}
}
